<template>
  <main>
    <div class="w-full">
      <FcDesigner
        ref="designer"
        class="h-[calc(100vh-120px)]"
        :config="config"
        :handle="handle"
        :locale="locale"
        left-width="350px"
        :code-data="codeData"
      >
        <template #handle>
          <div class="flex items-center gap-2 mr-2">
            <el-button type="success" size="small" @click="openAiDesign()">AI设计</el-button>
            <el-button type="primary" size="small" @click="openDiyList()">DIY列表</el-button>
            <el-button type="danger" size="small" @click="saveDiy()">保存</el-button>
            <el-button type="primary" size="small" @click="openPreview()">预览</el-button>
          </div>
        </template>
      </FcDesigner>
    </div>

    <el-dialog v-model="state" :title="title[type]" class="_fc-t-dialog" width="800px">
      <div v-if="state" ref="editor"></div>
      <span v-if="err" class="text-red-500">输入内容格式有误!</span>
      <template v-if="type > 2" #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="state = false">取 消</el-button>
          <el-button type="primary" size="small" @click="onOk">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- DIY列表弹窗 -->
    <el-dialog v-model="diyListDialog" title="DIY列表" width="800px" :z-index="900">
      <div class="w-full">
        <el-table :data="diyList" class="w-full" highlight-current-row @row-click="selectDiy">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="组件标识" width="150" />
          <el-table-column prop="label" label="组件名称" width="150" />
          <el-table-column prop="remark" label="备注" />
          <el-table-column prop="create_time" label="创建时间" width="180">
            <template #default="scope">
              {{ formatTime(scope.row.create_time) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button type="primary" size="small" @click.stop="loadDiy(scope.row)"> 选择 </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="mt-5 text-center">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="getDiyList"
            @current-change="getDiyList"
          />
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="diyListDialog = false">取消</el-button>
          <el-button type="primary" @click="createNewDiy">新建DIY</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- AI设计弹窗 -->
    <el-dialog v-model="aiDesignDialog" title="AI设计助手" width="800px" :z-index="900">
      <div v-if="!aiGenerating && !showGenerationResult">
        <el-form :model="aiDesignForm" label-width="120px" label-position="left">
          <el-form-item label="设计需求">
            <el-input
              v-model="aiDesignForm.prompt"
              type="textarea"
              :rows="4"
              placeholder="请详细描述您的表单设计需求，例如：我需要一个用户注册表单，包含姓名、邮箱、密码等字段..."
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="参考图片(可选)">
            <dk-image-input v-model="aiDesignForm.image" />
            <div class="mt-2">
              <el-text size="small" type="info"> 支持上传设计稿或参考图片，AI将根据图片内容生成相应的表单结构 </el-text>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <!-- AI生成过程展示 -->
      <div v-if="aiGenerating || showGenerationResult" class="min-h-100">
        <div class="generation-header">
          <el-icon v-if="aiGenerating" class="mr-2 animate-spin"><Loading /></el-icon>
          <el-icon v-else class="mr-2 text-green-500">
            <el-icon><SuccessFilled /></el-icon>
          </el-icon>
          <span class="text-base font-medium text-primary-600">
            {{ aiGenerating ? 'AI正在生成设计中...' : 'AI设计生成完成' }}
          </span>
        </div>

        <div class="mb-5">
          <el-steps :active="getProgressStep()" align-center>
            <el-step title="分析需求" />
            <el-step title="生成配置" />
            <el-step title="生成代码" />
            <el-step title="应用设计" />
          </el-steps>
        </div>

        <div
          ref="aiGenerationLog"
          class="h-50 overflow-y-auto border border-gray-200 rounded p-3 bg-gray-50 font-mono text-xs leading-relaxed mb-4"
        >
          <div v-for="(log, index) in aiGenerationLog" :key="index" :class="['mb-1 break-words', getLogClass(log.type)]">
            <span class="text-gray-400 mr-2">[{{ log.timestamp }}]</span>
            <span class="whitespace-pre-wrap">{{ log.content }}</span>
          </div>
        </div>
        <!-- 实时显示生成的内容 -->
        <div v-if="currentDiyData || codeData" class="mt-4">
          <el-tabs v-model="previewTab" type="border-card">
            <el-tab-pane v-if="currentDiyData" label="DIY配置" name="diyData">
              <pre class="code-preview">{{ formatJsonPreview(currentDiyData) }}</pre>
            </el-tab-pane>
            <el-tab-pane v-if="codeData" label="Vue代码" name="vueCode">
              <pre class="code-preview">{{ codeData }}</pre>
            </el-tab-pane>
            <el-tab-pane v-if="aiGenerationStep === 'vue_code' || aiGenerationStep === 'complete'" label="组件预览" name="componentPreview">
              <div class="component-preview">
                <!-- 错误信息显示 -->
                <div v-if="componentError" class="error-display">
                  <h4 class="m-0 mb-3 text-sm">渲染错误：</h4>
                  <pre class="error-pre">{{ componentError }}</pre>
                </div>

                <!-- 动态组件渲染区域 -->
                <div v-else-if="dynamicComponent" class="component-wrapper">
                  <component :is="dynamicComponent" :key="componentKey" />
                </div>

                <!-- 等待组件生成 -->
                <div v-else class="component-waiting">
                  <div v-if="aiGenerationStep === 'vue_code'">
                    <el-icon class="mr-2 animate-spin"><Loading /></el-icon>
                    <p>正在生成Vue组件代码，请稍候...</p>
                  </div>
                  <div v-else>
                    <p>等待Vue组件代码生成完成后进行预览</p>
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>

      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button @click="aiDesignDialog = false"> 关闭 </el-button>
          <el-button v-if="!aiGenerating && !showGenerationResult" type="primary" @click="generateAiDesign"> 开始AI设计 </el-button>
          <el-button v-if="aiGenerating" type="danger" @click="stopAiGeneration"> 停止生成 </el-button>
          <el-button v-if="showGenerationResult" type="success" @click="regenerateAiDesign"> 重新生成 </el-button>
        </div>
      </template>
    </el-dialog>
  </main>
</template>
<script>
import jsonlint from 'jsonlint-mod'
import CodeMirror from 'codemirror/lib/codemirror'

import { ElMessage } from 'element-plus'
import { Loading, SuccessFilled } from '@element-plus/icons-vue'
import { saveDesign, getList, getById } from '@/api/diy.js'
import { getToken } from '@/utils/auth'
import { shallowRef, markRaw } from 'vue'
import * as Vue from 'vue'

const TITLE = ['生成规则', '表单规则', '生成组件', '设置生成规则', '设置表单规则']
export default {
  components: {
    Loading,
    SuccessFilled
  },
  data() {
    return {
      state: false,
      value: null,
      title: TITLE,
      editor: null,
      err: false,
      type: -1,
      autoSaveId: null,
      lang: 'cn',
      locale: null,
      // hashData,
      topImg: true,
      config: {
        autoActive: true,
        fieldReadonly: false,
        showSaveBtn: true
      },
      handle: [
        {
          label: '中英切换',
          handle: () => {}
        }
      ],
      // DIY相关数据
      currentDiyId: 0, // 当前编辑的DIY ID
      diyListDialog: false,
      diyList: [],
      pagination: {
        page: 1,
        size: 10,
        total: 0
      },
      // AI设计相关数据
      aiDesignDialog: false,
      aiGenerating: false,
      aiDesignForm: {
        prompt: '',
        image: ''
      },
      // AI生成过程数据
      aiGenerationLog: [],
      currentDiyData: '',
      codeData: '',
      aiGenerationStep: '', // 'diy_data', 'vue_code', 'complete'
      previewTab: 'diyData', // 预览标签页
      abortController: null, // 用于中止请求
      // 动态组件预览相关
      dynamicComponent: null,
      componentError: '',
      showComponentPreview: false,
      componentKey: 0,
      // 控制生成结果显示
      showGenerationResult: false
    }
  },
  watch: {
    state(n) {
      if (!n) {
        this.value = null
        this.err = false
      }
    },
    value() {
      this.load()
    }
  },
  beforeCreate() {
    window.jsonlint = jsonlint
  },
  mounted() {
    // 从路由参数获取diy_id
    const diyId = this.$route.query.diy_id
    if (diyId) {
      this.currentDiyId = parseInt(diyId)
      this.loadDiyById(this.currentDiyId)
    } else {
      this.setJson()
    }

    // 添加键盘快捷键监听
    this.addKeyboardListeners()
  },
  beforeUnmount() {
    // 移除键盘监听器
    this.removeKeyboardListeners()
    // 清理动态组件
    this.cleanupDynamicComponent()
  },
  methods: {
    goBack() {
      this.$router.push('/home')
    },
    // 保存DIY数据
    async saveDiy() {
      const config = this.$refs.designer.get()
      console.log('saveDiy', config)

      // 检查必要字段
      if (!config.preferenceData || !config.preferenceData.name || !config.preferenceData.label) {
        ElMessage.warning('请设置组件标识和组件名称')
        return
      }

      try {
        // 调用新的API接口，传递 diyData, codeData, diy_id 三个参数
        const res = await saveDesign(config, this.codeData, this.currentDiyId)
        ElMessage.success(res.msg || '保存成功')

        // 如果是新增，更新当前ID和路由
        if (res.other && res.other.op === 'add') {
          this.currentDiyId = res.data.id
          this.$router.replace({
            path: '/diy',
            query: { diy_id: res.data.id }
          })
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败，请稍后重试')
      }
    },
    setJson() {
      // 这里从本地缓存获取数据
      try {
        const storedConfig = localStorage.getItem('designerConfig')
        if (storedConfig) {
          const value = JSON.parse(storedConfig)
          this.$refs.designer.set(value)
        }
      } catch (e) {
        console.error('Failed to read config from local storage:', e)
      }
    },
    openPreview() {
      this.$refs.designer.openPreview()
    },
    showJson() {
      this.state = true
      this.type = 0
      this.value = this.$refs.designer.getRule()
    },
    load() {
      let val
      if (this.type === 2) {
        val = this.value
      } else if (this.type === 0) {
        val = formCreate.toJson(this.value, 2)
      } else {
        val = JSON.stringify(this.value, null, 2)
      }
      this.$nextTick(() => {
        this.editor = CodeMirror(this.$refs.editor, {
          lineNumbers: true,
          mode: this.type === 2 ? { name: 'vue' } : 'application/json',
          gutters: ['CodeMirror-lint-markers'],
          lint: true,
          line: true,
          tabSize: 2,
          lineWrapping: true,
          value: val || ''
        })
        // 设置CodeMirror编辑器内部的高度
        // const editorHeight = '70vh' // 或者使用其他单位如百分比、vh等
        // this.editor.setSize(null, editorHeight) // 第一个参数为宽度，null表示保持不变；第二个参数为高度
        this.editor.on('blur', () => {
          this.err = this.editor.state.lint.marked.length > 0
        })
      })
    },
    // DIY列表相关方法
    openDiyList() {
      this.diyListDialog = true
      this.getDiyList()
    },
    async getDiyList() {
      try {
        const res = await getList(this.pagination.page, this.pagination.size, {})
        this.diyList = res.data || []
        this.pagination.total = res.count || 0
      } catch (error) {
        console.error('获取DIY列表失败:', error)
        ElMessage.error('获取DIY列表失败')
      }
    },
    selectDiy(row) {
      // 表格行点击事件
      this.loadDiy(row)
    },
    async loadDiy(row) {
      try {
        this.currentDiyId = row.id
        this.diyListDialog = false

        // 更新路由
        this.$router.replace({
          path: '/diy',
          query: { diy_id: row.id }
        })

        // 加载DIY数据
        await this.loadDiyById(row.id)
        ElMessage.success(`已切换到：${row.label}`)
      } catch (error) {
        console.error('加载DIY数据失败:', error)
        ElMessage.error('加载DIY数据失败')
      }
    },
    async loadDiyById(id) {
      try {
        const res = await getById(id)
        if (res.data) {
          // 加载DIY配置数据
          if (res.data.diyData) {
            this.$refs.designer.set(res.data.diyData)
          }

          // 加载Vue组件代码数据
          if (res.data.codeData) {
            this.codeData = res.data.codeData
            console.log('加载的Vue代码数据:', this.codeData)

            // 如果有代码数据，编译组件以便预览
            if (this.codeData.trim()) {
              await this.compileVueComponent()
            }
          }
        }
      } catch (error) {
        console.error('加载DIY数据失败:', error)
        ElMessage.error('加载DIY数据失败')
      }
    },
    createNewDiy() {
      this.currentDiyId = 0
      this.diyListDialog = false

      // 清空路由参数
      this.$router.replace({ path: '/diy' })

      // 清空代码数据
      this.codeData = ''
      this.cleanupDynamicComponent()

      // 重置设计器
      this.$refs.designer.set({
        rule: [],
        defaultData: {},
        preferenceData: {
          fixed: true,
          count: 1,
          label: '新组件',
          name: 'new-component',
          icon: 'icon-park:align-text-both-one'
        }
      })

      ElMessage.success('已创建新的DIY组件')
    },
    // 键盘快捷键相关方法
    addKeyboardListeners() {
      document.addEventListener('keydown', this.handleKeyDown)
    },
    removeKeyboardListeners() {
      document.removeEventListener('keydown', this.handleKeyDown)
    },
    handleKeyDown(event) {
      // Ctrl+S 保存
      if (event.ctrlKey && event.key === 's') {
        event.preventDefault()
        this.saveDiy()
      }
    },
    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp * 1000) // 假设是Unix时间戳
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    },
    // AI设计相关方法
    openAiDesign() {
      this.aiDesignDialog = true
      // 重置表单数据
      this.aiDesignForm = {
        prompt: '',
        image: ''
      }
      // 重置生成过程数据
      this.aiGenerationLog = []
      this.currentDiyData = ''
      // 不清空 codeData，因为加载DIY数据时需要用到
      // this.codeData = ''
      this.aiGenerationStep = ''
      this.previewTab = 'diyData'
      this.componentError = ''
      this.showComponentPreview = false
      this.showGenerationResult = false // 隐藏之前的生成结果
      // 清理动态组件
      this.cleanupDynamicComponent()
    },
    async generateAiDesign() {
      if (!this.aiDesignForm.prompt.trim()) {
        ElMessage.warning('请输入设计需求')
        return
      }

      // 检查是否有当前DIY ID
      if (!this.currentDiyId) {
        ElMessage.warning('请先创建或选择一个DIY组件')
        return
      }

      this.aiGenerating = true
      this.aiGenerationLog = []
      this.currentDiyData = ''
      // 开始新的AI生成时清空代码数据
      this.codeData = ''
      this.aiGenerationStep = ''
      this.cleanupDynamicComponent()

      try {
        await this.streamAiRequest()
      } catch (error) {
        console.error('AI设计生成失败:', error)
        ElMessage.error('AI设计生成失败，请稍后重试')
        this.aiGenerating = false
      }
    },
    // 流式请求处理AI生成
    async streamAiRequest() {
      const path = '/' + import.meta.env.VITE_BASE_ADDON_NAME + '/agent/'
      const requestUrl = import.meta.env.VITE_BASE_URL + path + 'diy'

      // this.addGenerationLog('info', `开始请求: ${requestUrl}`)
      this.addGenerationLog('info', `DIY ID: ${this.currentDiyId}`)

      // 创建 AbortController 用于中止请求
      this.abortController = new AbortController()

      try {
        const response = await fetch(requestUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Access-Token': this.getToken()
          },
          body: JSON.stringify({
            diy_id: this.currentDiyId,
            prompt: this.aiDesignForm.prompt,
            image: this.aiDesignForm.image
          }),
          signal: this.abortController.signal
        })

        this.addGenerationLog('info', `响应状态: ${response.status}`)

        if (!response.ok) {
          const errorText = await response.text()
          throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`)
        }

        const reader = response.body.getReader()
        const decoder = new TextDecoder()

        let buffer = '' // 用于累积接收到的数据
        let currentSection = '' // 当前处理的段落
        let streamCompleted = false

        while (true) {
          const { done, value } = await reader.read()
          if (done) {
            // 处理最后剩余的buffer内容
            if (buffer.trim()) {
              this.processBuffer(buffer, currentSection)
            }
            this.completeGeneration()
            break
          }

          const chunk = decoder.decode(value, { stream: true })
          buffer += chunk

          console.log('收到chunk:', chunk)
          console.log('当前buffer:', buffer)

          // 检查是否有错误信息
          if (buffer.includes('Error:')) {
            const errorMatch = buffer.match(/Error:\s*(.+?)(?=\n|$)/)
            if (errorMatch) {
              const errorMsg = errorMatch[1]
              this.addGenerationLog('error', errorMsg)
              ElMessage.error(errorMsg)
              this.aiGenerating = false
              return
            }
          }

          // 处理段落标记
          if (buffer.includes('===DIY_DATA_START===')) {
            currentSection = 'diy_data'
            this.aiGenerationStep = 'diy_data'
            this.addGenerationLog('info', '开始接收DIY配置数据...')
            buffer = buffer.replace('===DIY_DATA_START===', '')
          }

          if (buffer.includes('===DIY_DATA_END===')) {
            // 处理DIY数据段落结束
            const beforeEnd = buffer.split('===DIY_DATA_END===')[0]
            if (beforeEnd.trim()) {
              this.currentDiyData += beforeEnd
            }
            this.addGenerationLog('success', 'DIY配置接收完成')
            ElMessage.success('DIY配置生成完成')
            buffer = buffer.replace(/.*===DIY_DATA_END===/s, '')
            currentSection = ''
          }

          if (buffer.includes('===VUE_CODE_START===')) {
            currentSection = 'vue_code'
            this.aiGenerationStep = 'vue_code'
            this.addGenerationLog('info', '开始接收Vue组件代码...')
            // 自动切换到Vue代码标签页
            this.previewTab = 'vueCode'
            buffer = buffer.replace('===VUE_CODE_START===', '')
          }

          if (buffer.includes('===VUE_CODE_END===')) {
            // 处理Vue代码段落结束
            const beforeEnd = buffer.split('===VUE_CODE_END===')[0]
            if (beforeEnd.trim()) {
              this.codeData += beforeEnd
            }
            this.addGenerationLog('success', 'Vue组件代码接收完成')
            ElMessage.success('Vue组件代码生成完成')

            // 代码完全接收完毕后，立即编译组件
            await this.compileVueComponent()

            buffer = buffer.replace(/.*===VUE_CODE_END===/s, '')
            currentSection = ''
            streamCompleted = true
          }

          // 处理当前段落的内容
          if (currentSection && !buffer.includes('===')) {
            this.processBuffer(buffer, currentSection)
            buffer = '' // 清空已处理的buffer
          }
        }
      } catch (error) {
        if (error.name === 'AbortError') {
          this.addGenerationLog('warning', '请求被用户中止')
          this.aiGenerating = false
          ElMessage.error('请求被用户中止')
          return
        }
        console.error('流式请求失败:', error)
        this.addGenerationLog('error', `请求失败: ${error.message}`)
        ElMessage.error(`请求失败: ${error.message}`)
        this.aiGenerating = false
      } finally {
        // 清理 AbortController
        this.abortController = null
      }
    },
    // 添加生成日志
    addGenerationLog(type, content) {
      this.aiGenerationLog.push({
        type,
        content,
        timestamp: new Date().toLocaleTimeString()
      })

      // 自动滚动到底部
      this.$nextTick(() => {
        const logContainer = this.$refs.aiGenerationLog
        if (logContainer) {
          logContainer.scrollTop = logContainer.scrollHeight
        }
      })
    },
    // 获取token的辅助方法
    getToken() {
      return getToken()
    },
    // 获取进度步骤
    getProgressStep() {
      switch (this.aiGenerationStep) {
        case 'diy_data':
          return 1
        case 'vue_code':
          return 2
        case 'complete':
          return 3
        default:
          return 0
      }
    },
    // 格式化JSON预览
    formatJsonPreview(jsonStr) {
      try {
        const parsed = JSON.parse(jsonStr)
        return JSON.stringify(parsed, null, 2)
      } catch (e) {
        return jsonStr
      }
    },
    // 处理缓冲区内容
    processBuffer(buffer, currentSection) {
      if (!buffer.trim()) return

      console.log(`处理${currentSection}内容:`, buffer)

      if (currentSection === 'diy_data') {
        this.currentDiyData += buffer
        this.addGenerationLog('content', buffer)
      } else if (currentSection === 'vue_code') {
        this.codeData += buffer
        this.addGenerationLog('content', buffer)
        // 不再实时编译，等待代码完全生成后再编译
        // this.realtimeCompileComponent()
      }
    },
    // 完成生成处理
    async completeGeneration() {
      this.aiGenerating = false
      this.aiGenerationStep = 'complete'
      this.showGenerationResult = true // 显示生成结果
      this.addGenerationLog('success', 'AI生成完成！')

      console.log('最终DIY数据:', this.currentDiyData)
      console.log('最终Vue代码:', this.codeData)

      // 应用生成的配置到设计器
      if (this.currentDiyData) {
        try {
          console.log('准备解析的DIY数据:', this.currentDiyData)

          // 清理和修复JSON数据
          let cleanDiyData = this.currentDiyData.trim()

          // 检查是否缺少开头的 {
          if (!cleanDiyData.startsWith('{')) {
            // 尝试找到第一个完整的JSON对象
            const firstBraceIndex = cleanDiyData.indexOf('{')
            if (firstBraceIndex > -1) {
              cleanDiyData = cleanDiyData.substring(firstBraceIndex)
              console.log('修复后的DIY数据（添加开头）:', cleanDiyData)
            } else {
              // 如果没有找到 {，尝试添加
              cleanDiyData = '{' + cleanDiyData
              console.log('修复后的DIY数据（手动添加开头）:', cleanDiyData)
            }
          }

          // 检查是否缺少结尾的 }
          if (!cleanDiyData.endsWith('}')) {
            cleanDiyData = cleanDiyData + '}'
            console.log('修复后的DIY数据（添加结尾）:', cleanDiyData)
          }

          const aiDiyConfig = JSON.parse(cleanDiyData)
          console.log('解析后的AI DIY配置:', aiDiyConfig)

          // 获取当前设计器的配置
          const currentConfig = this.$refs.designer.get()
          console.log('当前设计器配置:', currentConfig)

          // 合并配置，只更新非null的部分
          const mergedConfig = { ...currentConfig }

          // 如果AI返回的rule不为null，则更新rule
          if (aiDiyConfig.rule !== null && aiDiyConfig.rule !== undefined) {
            mergedConfig.rule = aiDiyConfig.rule
            console.log('更新rule配置')
          } else {
            console.log('保持现有rule配置不变')
          }

          // 如果AI返回的defaultData不为null，则更新defaultData
          if (aiDiyConfig.defaultData !== null && aiDiyConfig.defaultData !== undefined) {
            mergedConfig.defaultData = aiDiyConfig.defaultData
            console.log('更新defaultData配置')
          } else {
            console.log('保持现有defaultData配置不变')
          }

          // 如果AI返回的preferenceData不为null，则更新preferenceData
          if (aiDiyConfig.preferenceData !== null && aiDiyConfig.preferenceData !== undefined) {
            mergedConfig.preferenceData = { ...mergedConfig.preferenceData, ...aiDiyConfig.preferenceData }
            console.log('更新preferenceData配置')
          } else {
            console.log('保持现有preferenceData配置不变')
          }

          // 将defaultData中的值应用到rule中的表单字段
          this.applyDefaultValuesToRules(mergedConfig)

          console.log('最终合并后的配置:', mergedConfig)
          this.$refs.designer.set(mergedConfig)
          ElMessage.success('AI设计已应用到设计器！')
        } catch (error) {
          console.error('解析diyData失败:', error, '原始数据:', this.currentDiyData)

          // 尝试更智能的修复
          try {
            let repairData = this.currentDiyData.trim()
            // 移除可能的前缀文本，寻找包含 "rule" 的JSON对象
            const jsonStart = repairData.search(/\{[\s\S]*"rule"/)
            if (jsonStart > -1) {
              repairData = repairData.substring(jsonStart)
              console.log('智能修复后的数据:', repairData)

              const aiDiyConfig = JSON.parse(repairData)
              const currentConfig = this.$refs.designer.get()

              // 同样的合并逻辑
              const mergedConfig = { ...currentConfig }
              if (aiDiyConfig.rule !== null && aiDiyConfig.rule !== undefined) {
                mergedConfig.rule = aiDiyConfig.rule
              }
              if (aiDiyConfig.defaultData !== null && aiDiyConfig.defaultData !== undefined) {
                mergedConfig.defaultData = aiDiyConfig.defaultData
              }
              if (aiDiyConfig.preferenceData !== null && aiDiyConfig.preferenceData !== undefined) {
                mergedConfig.preferenceData = { ...mergedConfig.preferenceData, ...aiDiyConfig.preferenceData }
              }

              // 将defaultData中的值应用到rule中的表单字段
              this.applyDefaultValuesToRules(mergedConfig)

              this.$refs.designer.set(mergedConfig)
              ElMessage.success('使用修复后的DIY配置应用成功！')
            } else {
              ElMessage.error('DIY配置格式错误，无法自动修复')
            }
          } catch (repairError) {
            console.error('智能修复DIY数据也失败:', repairError)
            ElMessage.error('DIY配置格式错误，请检查生成的数据')
          }
        }
      } else {
        console.log('没有收到DIY数据')
        ElMessage.warning('没有收到有效的DIY配置数据')
      }

      // 编译并预览最终的Vue组件（如果还没有编译的话）
      if (this.codeData && !this.dynamicComponent) {
        await this.compileVueComponent()
      }

      // 生成完成后自动切换到组件预览标签页
      if (this.codeData) {
        this.previewTab = 'componentPreview'
      }
    },
    // 编译Vue组件
    async compileVueComponent() {
      if (!this.codeData.trim()) {
        this.componentError = '没有Vue组件代码'
        return
      }

      try {
        // 先清理旧组件
        this.cleanupDynamicComponent()

        this.componentError = ''
        console.log('开始编译Vue组件:', this.codeData)

        // 解析Vue单文件组件
        const templateMatch = this.codeData.match(/<template>([\s\S]*?)<\/template>/)
        const scriptMatch = this.codeData.match(/<script[^>]*>([\s\S]*?)<\/script>/)
        const styleMatch = this.codeData.match(/<style[^>]*>([\s\S]*?)<\/style>/)

        if (!templateMatch) {
          throw new Error('未找到template标签')
        }

        const template = templateMatch[1].trim()
        const script = scriptMatch ? scriptMatch[1].trim() : ''
        const style = styleMatch ? styleMatch[1].trim() : ''

        console.log('解析结果:', { template, script, style })

        // 创建组件选项
        let componentOptions = {}

        if (script) {
          // 处理script内容，移除export default
          const scriptContent = script.replace(/export\s+default\s*/, '')

          // 如果script内容是一个对象字面量，直接解析
          if (scriptContent.trim().startsWith('{') && scriptContent.trim().endsWith('}')) {
            try {
              // 使用Function构造器安全地解析对象
              // eslint-disable-next-line no-new-func
              const func = new Function('return ' + scriptContent)
              componentOptions = func()
            } catch (e) {
              console.error('Script解析失败:', e)
              componentOptions = {}
            }
          } else {
            // 如果不是对象字面量，尝试用eval
            try {
              // eslint-disable-next-line no-eval
              componentOptions = eval('(' + scriptContent + ')')
            } catch (e) {
              console.error('Script执行失败:', e)
              componentOptions = {}
            }
          }
        }

        // 检查Vue编译器是否可用
        if (!Vue.compile) {
          throw new Error('Vue编译器不可用，请确保使用完整版Vue')
        }

        // 编译模板
        const render = Vue.compile(template)

        // 创建最终组件
        const componentId = `ai-component-${Date.now()}`
        const finalComponent = {
          name: componentOptions.name || 'AIGeneratedComponent',
          ...componentOptions,
          render,
          __scopeId: style ? `data-v-${componentId}` : undefined,
          // 添加错误边界
          errorCaptured(err, vm, info) {
            console.error('组件运行时错误:', err, info)
            return false
          }
        }

        // 如果有样式，动态添加到页面
        if (style) {
          this.addDynamicStyle(style, componentId, finalComponent.__scopeId)
        }

        // 更新组件key以强制重新渲染
        this.componentKey++
        // 使用 markRaw 标记组件，避免Vue将其转为响应式对象
        this.dynamicComponent = markRaw(finalComponent)
        console.log('组件编译成功:', finalComponent)
      } catch (error) {
        console.error('组件编译失败:', error)
        this.componentError = `组件编译失败: ${error.message}`
        this.cleanupDynamicComponent()
      }
    },
    // 添加动态样式
    addDynamicStyle(style, componentId, scopeId) {
      const styleId = `ai-style-${componentId}`

      // 移除之前的样式
      const existingStyle = document.getElementById(styleId)
      if (existingStyle) {
        existingStyle.remove()
      }

      const styleElement = document.createElement('style')
      styleElement.id = styleId

      // 处理scoped样式
      let processedStyle = style
      if (scopeId) {
        processedStyle = style.replace(/([^{}]+)\{/g, (match, selector) => {
          // 为每个选择器添加scope属性
          const selectors = selector
            .split(',')
            .map((s) => {
              const trimmed = s.trim()
              return `${trimmed}[${scopeId}]`
            })
            .join(', ')
          return `${selectors} {`
        })
      }

      styleElement.textContent = processedStyle
      document.head.appendChild(styleElement)
    },
    // 清理动态组件
    cleanupDynamicComponent() {
      if (this.dynamicComponent) {
        // 清理旧组件
        this.dynamicComponent = null
        this.componentKey++

        // 清理可能的定时器或事件监听器
        this.$nextTick(() => {
          // 强制垃圾回收
          if (window.gc) {
            window.gc()
          }
        })
      }
    },
    // 重新生成AI设计
    regenerateAiDesign() {
      // 隐藏生成结果，显示表单让用户重新输入
      this.showGenerationResult = false
      // 不直接开始生成，而是回到表单状态
    },
    // 停止AI生成
    stopAiGeneration() {
      this.aiGenerating = false
      this.addGenerationLog('warning', '用户停止了生成过程')
      // 清理动态组件
      this.cleanupDynamicComponent()
      // 如果有正在进行的请求，尝试中止
      if (this.abortController) {
        this.abortController.abort()
        this.abortController = null
      }
    },
    // 获取日志样式类
    getLogClass(type) {
      const classMap = {
        info: 'text-blue-600',
        success: 'text-green-600',
        error: 'text-red-600',
        warning: 'text-yellow-600',
        content: 'text-gray-600'
      }
      return classMap[type] || 'text-gray-600'
    },
    // 将defaultData中的值应用到rule中的表单字段
    applyDefaultValuesToRules(config) {
      if (!config.defaultData || !config.rule || !Array.isArray(config.rule)) {
        console.log('没有defaultData或rule配置，跳过应用默认值')
        return
      }

      console.log('开始应用默认值到rule字段:', config.defaultData)

      // 递归遍历rule数组，为每个字段设置默认值
      const applyValuesToRuleItems = (rules, defaultData) => {
        rules.forEach((rule) => {
          // 如果rule有field属性且在defaultData中有对应的值
          if (rule.field && Object.prototype.hasOwnProperty.call(defaultData, rule.field)) {
            const defaultValue = defaultData[rule.field]
            // 设置value属性
            rule.value = defaultValue
            console.log(`为字段 ${rule.field} 设置默认值:`, defaultValue)
          }

          // 如果rule有children，递归处理
          if (rule.children && Array.isArray(rule.children)) {
            applyValuesToRuleItems(rule.children, defaultData)
          }
        })
      }

      applyValuesToRuleItems(config.rule, config.defaultData)
      console.log('默认值应用完成，更新后的rule:', config.rule)
    }
  }
}
</script>

<style>
/* 保留必要的深度选择器和动态组件样式隔离 */
:deep(.el-tabs__content) {
  padding: 0;
}

:deep(.el-tab-pane) {
  max-height: 300px;
  overflow-y: auto;
}

/* 动态组件样式隔离 */
.component-wrapper > * {
  max-width: 100%;
}

.component-wrapper {
  isolation: isolate;
}
</style>
